// 我的足迹
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: [],
    cart: false,
    num: 1,
    // 选择商品的价格
    price: "",
    // 选择商品的图片
    pic: "",
    // 商品的属性
    attr: [],
    // 选择的商品属性
    attrcart: [],
    // 根据属性变化的价格
    prices: "",
    // 库存
    stock: "",
    p_id: "",
    // 添加购物车的商品
    product: {},
    p:1,
    noMore:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var m_id = app.globalData.user.m_id;
    var p =this.data.p;
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Member/mySpoor',
      data:{
        m_id:m_id,
        p:p
      },
      header:{
        "content-type":"application/x-www-form-urlencoded"
      },
      method:"POST",
      success:function(res){
        var time = res.data.data;
        this.setData({
          time:time
        })
      }.bind(this),
      fail:function(res){
        wx.showModal({
          title: '提示',
          content: res.data.message,
          showCancel:false
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var m_id = app.globalData.user.m_id;
    var p = this.data.p;
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Member/mySpoor',
      data: {
        m_id: m_id,
        p: p
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      success: function (res) {
        var time = res.data.data;
        this.setData({
          time: time
        })
      }.bind(this),
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: res.data.message,
          showCancel: false
        })
      }
    })
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var noMore = this.data.noMore;
    if(noMore == false){
      var time = this.data.time;
      var m_id = app.globalData.user.m_id;
      var p = this.data.p;
      p = p + 1;
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Member/mySpoor',
        data: {
          m_id: m_id,
          p: p
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          var timer = res.data.data;
          if (timer != "") {
            time.push(timer)
          } else {
            noMore = true
          }
          this.setData({
            time: time,
            noMore: noMore
          })
        }.bind(this),
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false
          })
        }
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.name,
      path: "/pages/shouye/shouye",
      imageUrl: app.globalData.headPic
    }
  },
  /**
   * 商品详情查看
   */
  detail:function(e){
    var one = e.currentTarget.dataset.one;
    var two = e.currentTarget.dataset.two;
    var time = this.data.time;
    app.globalData.productModel = time[one].list[two];
    wx.navigateTo({
      url: '/pageA/detail/detail',
    })
  },
  /**
   * 选择删除足迹或者添加购物车/添加购物车暂时做到跳转详情页
   */
  choose:function(e){
    var id = e.currentTarget.dataset.idx;
    var one = e.currentTarget.dataset.one;
    var two = e.currentTarget.dataset.two;
    var time = this.data.time;
    var product = time[one].list[two]
    var p_id = product.p_id;
    wx.showActionSheet({
      itemList: ["删除","添加购物车"],
      success:function(res){
        if(res.tapIndex == 0){
          //删除足迹
          wx.request({
            url: app.globalData.yuming + 'merchant.php/Api/Member/delSpoor',
            data: {
              id: id
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function (res) {
              time[one].list.splice(two, 1)
              this.setData({
                time: time
              })
            }.bind(this),
            fail:function(res){
              wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel: false
              })
            }
          })
        } else if (res.tapIndex == 1){
          var pic = product.pic;
          var prices = product.price;
          var stock = product.stock;
          var cart = !this.data.cart;
          this.setData({
            cart: cart,
            pic: pic,
            prices: prices,
            p_id: p_id,
            product: product,
            stock: stock
          })
          this.getAttr(p_id)
        }
      }.bind(this)
    })    
  },
  // 获取商品属性
  getAttr: function (p_id) {
    var attr = this.data.attr;
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Product/productAttr',
      data: {
        p_id: p_id
      },
      header: {
        "content-type": "application/json"
      },
      success: function (res) {
        attr = res.data.data;
        var attrcart =[];
        this.setData({
          attr: attr,
          attrcart: attrcart
        })
      }.bind(this)
    })
  },
  // 关闭选项卡
  closeCart: function () {
    var cart = !this.data.cart;
    this.setData({
      cart: cart
    })
  },
  /**
   * 选择属性
   */
  checked: function (e) {
    var that = this;
    var p_id = this.data.p_id;
    var val_id = e.currentTarget.dataset.index;
    var attr = this.data.attr;
    // 获取商品属性串
    var attrcart = this.data.attrcart;
    // 同一个属性，只能选择一个属性值
    for (var i = 0, length = attr.length; i < length; i++) {
      var item = attr[i].attr_val;
      for (var j = 0, l = item.length; j < l; j++) {
        if (item[j].val_id == val_id) {

          for (var n = 0; n < l; n++) {
            var v_id = item[n].val_id;
            for (var p = 0, m = attrcart.length; p <= m; p++) {
              if (attrcart[p] == v_id) {
                attrcart.splice(p, 1)
              }
            }
            item[n]['checked'] = false;
          }
          item[j]['checked'] = true;
        }
      }
    }
    attrcart.push(val_id);
    attrcart.sort()
    // 判断全部属性都已经选择了以后，请求当前属性对应的价格和库存
    if (attrcart.length == attr.length) {
      var att = attrcart[0];
      for (var i = 1, length = attrcart.length; i < length; i++) {
        att = att + "|" + attrcart[i];
      }
      // 获取当前属性的价格和库存
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Product/productPrice',
        data: {
          p_id: p_id,
          attr: att
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          var prices = res.data.data.price;
          var stock = res.data.data.stock;
          if (stock == 0) {
            wx.showModal({
              title: '提示',
              content: '库存为0',
              showCancel: false,
              success: function () {
                that.setData({
                  stock: 0
                })
              }
            })
          } else {
            that.setData({
              prices: prices,
              stock: stock
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false
          })
        }
      })
    }
    that.setData({
      attrcart: attrcart.sort(),
      attr: attr
    })
  },
  /**
   * 加号
   */
  buyAdd: function () {
    var num = this.data.num;
    var stock = this.data.stock;
    if (num >= stock) {
      wx.showModal({
        title: '提示',
        content: '库存不足',
        showCancel: false
      })
    } else {
      num += 1;
    }
    this.setData({
      num: num
    })
  },
  /**
   * 减号
   */
  buyMini: function () {
    var num = this.data.num;
    var stock = this.data.stock;
    if (num == 1) {
      wx.showModal({
        title: '提示',
        content: '不能少于一件',
        showCancel: false
      })
    } else {
      if (num > stock) {
        wx.showModal({
          title: '提示',
          content: '库存:' + stock,
          showCancel: false
        })
        num = Number(stock)
      } else {
        num = num - 1;
      }

      this.setData({
        num: num
      })
    }

  },
  /**
 * 确定加入购物车
 */
  goshopCart: function () {
    var that = this;
    var m_id = app.globalData.user.m_id;
    var shop_id = this.data.product.shop_id;
    var product = this.data.product;
    var p_id = product.p_id;
    var num = this.data.num;
    var attrcart = this.data.attrcart;
    var attr = attrcart[0];
    var typee = this.data.product.type;
    // 判断商品属性是否选择完全
    for (var i = 1, length = attrcart.length; i < length; i++) {
      attr = attr + "|" + attrcart[i];
    }
    if (typee != 1) {
      var attrA = that.data.attr;
      for (var j = 0, l = attrA.length; j < l; j++) {
        var val = attrA[j];
        var a = 0;
        for (var m = 0, ll = val.attr_val.length; m < ll; m++) {
          for (var i = 0, length = attrcart.length; i < length; i++) {
            if (val.attr_val[m].val_id == attrcart[i]) {
              a = a + 1;
            } else {
              a = a + 0;
            }
          }
        }
        if (a == 0) {
          wx.showModal({
            title: '提示',
            content: "请选择" + val.attr_name.attr_name,
            showCancel: false
          })
          console.log(val.attr_name.attr_name)
          return;
        }
      }
      var price = this.data.prices;
      // 请求库存量，如果库存为0，提示库存不足，如果不为0，添加购物车
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Product/productPrice',
        data: {
          p_id: p_id,
          attr: attr
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          var stock = res.data.data.stock;
          price = res.data.data.price
          if (stock != 0) {
            wx.request({
              url: app.globalData.yuming + 'merchant.php/Api/Cart/addCart',
              data: {
                m_id: m_id,
                shop_id: shop_id,
                p_id: p_id,
                num: num,
                attr: attr,
                price: price
              },
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              method: "POST",
              success: function (res) {
                wx.showToast({
                  title: res.data.message,
                  image: "../../images/success.png",
                  success: function () {
                    var cart = !that.data.cart;
                    setTimeout(function () {
                      that.setData({
                        cart: cart
                      })
                    }, 500)

                  }
                })

              },
              fail: function (res) {
                wx.showModal({
                  title: '提示',
                  content: res.data.message,
                  showCancel: false
                })
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '库存不足！',
              showCancel: false
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
          })
        }
      })
    } else {
      attr = ""
      var price = this.data.prices;
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Cart/addCart',
        data: {
          m_id: m_id,
          shop_id: shop_id,
          p_id: p_id,
          num: num,
          attr: attr,
          price: price
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          wx.showToast({
            title: res.data.message,
            image: "../../images/success.png",
            success: function () {
              var cart = !that.data.cart;
              setTimeout(function () {
                that.setData({
                  cart: cart
                })
              }, 500)

            }
          })

        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false
          })
        }
      })
    }
  }
})